//
//  BLogin.m
//  car
//
//  Created by chenxu on 4/14/15.
//  Copyright (c) 2015 chenxu. All rights reserved.
//

#import "BLogin.h"
#import "BPush.h"
#define kLoginStatus @"company_status"
#define kLoginCompanyId @"company_id"
#define kLoginCompanyDict @"company_dict"

static Company *curCompany;

@implementation BLogin


/*!
 *  @brief  清除里面的null换成@""
 *  @param dictionary 待处理的
 */
+ (void)cleanDictionary:(NSMutableDictionary *)dictionary {
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if (obj == [NSNull null]) {
            [dictionary setValue:@"" forKey:key];
        } else if ([obj isKindOfClass:[NSDictionary class]]) {
            [self cleanDictionary:obj];
        }
    }];
    
}


#pragma mark    Login
+ (BOOL) isLogin{
    NSNumber *loginStatus = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginStatus];
    if (loginStatus.boolValue && [BLogin curCompany]) {
        return YES;
    }else{
        return NO;
    }
}

+ (void) doLogin:(NSDictionary *)loginData{
    if (loginData) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //持久化
        [defaults setObject:[NSNumber numberWithBool:YES] forKey:kLoginStatus];
        
        NSMutableDictionary* temp = [[NSMutableDictionary alloc]initWithDictionary:loginData];
        
        
        [self cleanDictionary:temp];
        //temp = [self lowercase:temp];
        
        [defaults setObject:temp forKey:kLoginCompanyDict];
        [defaults synchronize];
        
        curCompany = [NSObject objectOfClass:@"Company" fromJSON:temp];
        
    }else{
        [Login doLogout];
    }
}

+ (void) doLogout{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSNumber numberWithBool:NO] forKey:kLoginStatus];
    [defaults synchronize];
}

+ (Company *)curCompany{
    if (!curCompany) {
        NSDictionary *loginData = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginCompanyDict];
        curCompany = loginData? [NSObject objectOfClass:@"Company" fromJSON:loginData]: nil;
    }
    return curCompany;
}

- (NSDictionary*)toLoginParams{
    return @{
             @"Businessname" : _username,
             @"Businesspassword" : _password,
             @"Buser_id" : [BPush getUserId],
             @"Bchannel_id" : [BPush getChannelId],
             @"device" : @"2"  //1安卓 2ios
             };
}



@end
